package com.jxl.springboot.game.service;

import com.jxl.springboot.game.mapper.GameTypeMapper;
import com.jxl.springboot.game.pojo.GameType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 游戏类型业务
 *
 * @author 江雪林
 * @create 2021-03-29
 */
@Service
public class GameTypeService {
    @Resource
    private GameTypeMapper gameTypeMapper;

    public List<GameType> getAll() {
        List<GameType> all = gameTypeMapper.findAll();
        List<GameType> tree = getTree(all);
        return tree;
    }

    /**
     * 获取菜单树
     *
     * @param all 所有菜单项数据
     * @return
     */
    private List<GameType> getTree(List<GameType> all) {
        List<GameType> roots = new ArrayList<GameType>();
        //获取父级
        for (GameType root : all) {
            if (root.getParentId() == 0) {
                roots.add(root);
            }
        }
        //获取父级的子级
        for (GameType root : roots) {
            root.setSubsTypes(this.getChild(root.getId(), all));
        }
        return roots;
    }

    /**
     * 递归获取子级
     *
     * @return
     */
    private List<GameType> getChild(int rootId, List<GameType> all) {
        //退出条件
        if (all.size() == 0) {
            return new ArrayList<GameType>();
        }
        //获取子节点
        List<GameType> childs = new ArrayList<GameType>();
        for (GameType child : all) {
            if (child.getParentId() == rootId) {
                childs.add(child);
            }
        }
        //获取子级的子级
        for (GameType child : childs) {
            child.setSubsTypes(getChild(child.getId(), all));
        }
        return childs;
    }
}
